<template>
  <div class="experiment-detail">
    <h2>{{ experiment.name }}</h2>
    <el-button type="primary" @click="handleBack">返回</el-button>
    <el-divider></el-divider>
    <h3>任务列表</h3>
    <div v-if="!experiment.tasks || experiment.tasks.length === 0">
      <p>暂无任务</p>
    </div>
    <div v-if="experiment.student_progress">
      <el-tag :type="experiment.student_progress.status === '已完成' ? 'success' : 'info'">
        {{ experiment.student_progress.status }}
      </el-tag>
      <div v-if="experiment.student_progress.status === '已完成'">
        <p>上次成绩：{{ experiment.student_progress.score }} / {{ experiment.student_progress.max_score }}</p>
      </div>
    </div>
    <div v-else>
        <div v-for="task in experiment.tasks" :key="task.id">
        <el-link
            :underline="false"
            @click="navigateToTask(experiment.id, task.id)"
            style="font-size: 18px; font-weight: bold;"
        >
            {{ task.name }}
        </el-link>
        </div>
    </div>
  </div>
</template>

<script>
// TaskComponent is not used here, was likely a leftover from previous structure
import axios from 'axios'; // Ensure axios is configured with auth token interceptor
import { useRouter } from 'vue-router'

export default {
  name: 'ExperimentDetailView',
  // components: { }, // Removed TaskComponent
  props: ['id'], // This 'id' is experiment.id from the route
  data() {
    return {
      experiment: {
        name: '',
        tasks: []
      },
      isLoading: false // For loading state
    };
  },
  mounted() {
    // const exid = this.$route.params.id; // or this.id if props:true in router
    this.fetchExperimentDetail(this.id);
  },
  methods: {
    async fetchExperimentDetail(experimentId) {
      this.isLoading = true;
      try {
        // Use public endpoint if task details within experiment don't need auth for viewing list
        // Or ensure your regular /api/experiments/${experimentId}/ is accessible
        console.log(experimentId)
        console.log(this.id)
        const res = await axios.get(`/api/public/experiments/${experimentId}/`); 
        this.experiment = res.data;
      } catch (error) {
        console.error('获取实验详情失败:', error);
        this.$message.error('获取实验详情失败，请重试。');
      } finally {
        this.isLoading = false;
      }
    },
    async navigateToTask(experimentId, taskId) {
      this.isLoading = true;
      try {
        // Call the new backend API to get or create StudentAnswerRecord
        const response = await axios.post('/api/student-answers/get-or-create-for-task/', {
          experiment_id: experimentId,
          task_id: taskId
          // student_id will be derived from the authenticated user on the backend
        });

        const studentAnswerRecordId = response.data.id;

        if (studentAnswerRecordId) {
          // Navigate to TaskDetailView with experimentId, taskId, and studentAnswerRecordId
          this.$router.push({
            name: 'task-detail', // Ensure you have a named route for tasks
            params: {
              expId: String(experimentId), // 确保是字符串
              taskId: String(taskId),       // 确保是字符串
              recordId: String(studentAnswerRecordId) // 确保是字符串
            }
          });
        } else {
          this.$message.error('无法准备任务，请重试。');
        }
      } catch (error) {
        console.error('准备任务失败:', error.response?.data || error.message);
        let errMsg = '准备任务失败，请重试。';
        if (error.response && error.response.data) {
            if (error.response.data.detail) errMsg = error.response.data.detail;
            else if (error.response.data.error) errMsg = error.response.data.error;
        }
        this.$message.error(errMsg);
      } finally {
        this.isLoading = false;
      }
    },
    goBack() {
      this.$router.push('/experiments');
    },
    handleBack() {
      const role = localStorage.getItem('role')
      if (role === 'teacher') {
        this.$router.push('/teacher/experiments')
      } else {
        this.$router.push('/experiments')
      }
    }
  }
};
</script>

<style scoped>
.experiment-detail {
  padding: 20px;
}
</style>